package com.onairm.baselibrary.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.onairm.baselibrary.Init;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bqy on 2018/3/26.
 */

public class BaseParamsUtils {
    private static String v;
    private static String dk;

    private BaseParamsUtils() {

    }

    private static class BaseHolder {
        private final static BaseParamsUtils base = new BaseParamsUtils();
    }

    public static BaseParamsUtils getInstance() {
        return BaseHolder.base;
    }

    /**
     * 获取userId
     *
     * @return
     */
    private String getUserId(String random) {
        String userId;
        if (SharePrefer.isLogined() && !TextUtils.isEmpty(SharePrefer.getUserId())) {
            userId = SharePrefer.getUserId();
        } else {
            userId = "a" + random;
        }
        return userId;
    }

    private String getToken(String userId, String ty, String v, String dk, String random) {
        String MD5String = MD5(userId + ty + v + dk);
        if (!SharePrefer.isLogined()) {
            return random + MD5String;
        } else {
            return SharePrefer.getToken() + MD5String;
        }
    }

    /**
     * 获取16位随机数
     *
     * @return
     */
    private String get16Random() {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String aa = MD5(sdf.format(d)).substring(1, 17).trim();
        return aa;
    }

    private String MD5(String key) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(key.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            String md5 = new BigInteger(1, md.digest()).toString(16);
            //BigInteger会把0省略掉，需补全至32位
            return fillMD5(md5);
        } catch (Exception e) {
            throw new RuntimeException("MD5加密错误:" + e.getMessage(), e);
        }
    }

    private String fillMD5(String md5) {
        return md5.length() == 32 ? md5 : fillMD5("0" + md5);
    }

    private static String getDeviceId() {
        Context context = Init.context;
        TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//        String szImei = TelephonyMgr.getDeviceId();
//        Log.e("getDeviceId", "getDeviceId===="+szImei);
        String m_szDevIDShort = "35" + //we make this look like a valid IMEI
                Build.BOARD.length() % 10 +
                Build.BRAND.length() % 10 +
                Build.CPU_ABI.length() % 10 +
                Build.DEVICE.length() % 10 +
                Build.DISPLAY.length() % 10 +
                Build.HOST.length() % 10 +
                Build.ID.length() % 10 +
                Build.MANUFACTURER.length() % 10 +
                Build.MODEL.length() % 10 +
                Build.PRODUCT.length() % 10 +
                Build.TAGS.length() % 10 +
                Build.TYPE.length() % 10 +
                Build.USER.length() % 10; //13 digits
        String m_szAndroidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
//        BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter
//        m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        String m_szBTMAC = "";
//        if (m_BluetoothAdapter != null) {
//            m_szBTMAC = m_BluetoothAdapter.getAddress();
//        }
//        String m_szLongID = szImei + m_szDevIDShort + m_szAndroidID + m_szWLANMAC + m_szBTMAC;
        String m_szLongID = m_szDevIDShort + m_szAndroidID + m_szWLANMAC + m_szBTMAC;

        // compute md5
        MessageDigest m = null;

        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        m.update(m_szLongID.getBytes(), 0, m_szLongID.length());
        // get md5 bytes
        byte p_md5Data[] = m.digest();
        // create a hex string
        String m_szUniqueID = new String();
        for (int i = 0; i < p_md5Data.length; i++) {
            int b = (0xFF & p_md5Data[i]);
            // if it is a single digit, make sure it have 0 in front (proper padding)
            if (b <= 0xF)
                m_szUniqueID += "0";
            // add number to string
            m_szUniqueID += Integer.toHexString(b);
        }   // hex string to uppercase
        m_szUniqueID = m_szUniqueID.toUpperCase();
        m_szDevIDShort = m_szUniqueID;
        dk = m_szDevIDShort;
        return m_szDevIDShort;
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static String getVersion() {
        Context context = Init.context;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            v = info.versionName;
            return v;
        } catch (Exception e) {
            e.printStackTrace();
            return "0.0";
        }
    }

    public static String getDK() {
        if (!TextUtils.isEmpty(dk)) {
            return dk;
        } else {
            return getDeviceId();
        }
    }

    public static String getV() {
        if (!TextUtils.isEmpty(v)) {
            return v;
        } else {
            return getVersion();
        }
    }

    public static String getTY() {
        return Utils.getProType();
    }


    public BaseParams getBaseParams() {
        BaseParams params = new BaseParams();
        String random = get16Random();
        String userId = getUserId(random);
        String ty = getTY();
        String dk = getDK();
        String v = getVersion();
        String token = getToken(userId, ty, v, dk, random);
        params.setToken(token);
        params.setUserId(userId);
        params.setDk(dk);
        params.setTy(ty);
        params.setV(v);
        return params;
    }

    public class BaseParams {
        private String userId;
        private String token;
        private String v;
        private String dk;
        private String ty;

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getToken() {
            return token;
        }

        public void setToken(String token) {
            this.token = token;
        }

        public String getV() {
            return v;
        }

        public void setV(String v) {
            this.v = v;
        }

        public String getDk() {
            return dk;
        }

        public void setDk(String dk) {
            this.dk = dk;
        }

        public String getTy() {
            return Utils.getProType();
        }

        public void setTy(String ty) {
            this.ty = ty;
        }
    }
}
